package com.zzzy.server.controller;

import com.google.code.kaptcha.Producer;
import com.zzzy.common.util.FileUtil;
import com.zzzy.common.vo.AjaxResult;
import com.zzzy.server.common.cache.VerifyCodeCache;
import com.zzzy.server.vo.VerifyCodeRes;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.io.FileUtils;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import java.util.UUID;

/**
 * Description: 验证码操作处理
 *
 * @author fc
 * @date 2024/4/15
 */

@Tag(name = "验证码", description = "server000")
@RestController
public class CaptchaController {
    @Resource
    private Producer captchaProducer;
    @Resource
    private VerifyCodeCache verifyCodeCache;

    @Operation(summary = "获取验证码")
    @GetMapping("/getVerifyCode")
    public AjaxResult<VerifyCodeRes> getVerifyCode() {
        String verifyKey = UUID.randomUUID().toString();
        // 生成验证码
        String verifyCode = captchaProducer.createText();
        verifyCodeCache.putVerifyCode(verifyKey, verifyCode);
        BufferedImage image = captchaProducer.createImage(verifyCode);
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }
        VerifyCodeRes verifyCodeRes = new VerifyCodeRes();
        verifyCodeRes.setVerifyKey(verifyKey);
        verifyCodeRes.setVerifyCodeImage(Base64.getEncoder().encodeToString(os.toByteArray()));
        return AjaxResult.success(verifyCodeRes);
    }

}
